package org.dubnation.auth.context;

import org.dubnation.base.interceptors.AuthenticInterceptor;
import org.dubnation.org.domain.Employee;
import org.dubnation.user.domain.LoginInfo;
import org.dubnation.user.mapper.LoginInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 登录上下文：把登录后的一些信息，缓存到这里面，其他地方来获取使用
 * 1 登录用户
 * 2 登录用户权限
 */
@Component
public class LoginContext {

    //注入静态redisTemplate
    private static RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate){
        LoginContext.redisTemplate = redisTemplate;
    }
    //注入静态loginInfoMapper
    private static LoginInfoMapper loginInfoMapper;
    @Autowired(required = false)
    public void setLoginInfoMapper(LoginInfoMapper loginInfoMapper){
        LoginContext.loginInfoMapper = loginInfoMapper;
    }

    /**
     * 登录成功后调用
     * @param loginUser
     */
    public static void setLoginAdmin(Employee loginUser){
        //暂时不实现--要存放session,redis

    }

    /**
     * 获取登录用户--Employee或User
     * @return
     */
    public static Object getLoginAdmin(){
        //1.根据前端传到后端的token将登录用户从redis中取出loginInfo
        String token = AuthenticInterceptor.loginToken;
        LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
        if (Objects.nonNull(loginInfo)){
            Integer loginInfoType = loginInfo.getType();
            //2.如果loginInfo是后台用户，返回Employee；如果是前台用户，返回User
            if (loginInfoType.equals(LoginInfo.TYPE_ADMINISTRATORS)){
                //根据loginInfo的id将对应的Employee查询出来并返回
                return loginInfoMapper.queryEmployee(loginInfo.getId());
            }else if (loginInfoType.equals(LoginInfo.TYPE_USER)){
                return loginInfoMapper.queryUser(loginInfo.getId());
            }
        }
        //没有登录过或登录已过期
        return null;
    }
}
